//
//  WBComposeTypeView.swift
//  daoge_sineweibo
//
//  Created by 伍禄林 on 16/10/19.
//  Copyright © 2016年 伍禄林. All rights reserved.
//

import UIKit
import pop
class WBComposeTypeView: UIView {

    
    @IBOutlet weak var scrollView: UIScrollView!
    
   
    @IBOutlet weak var returnBtn: UIButton!
    
    @IBOutlet weak var returnBtnCons: NSLayoutConstraint!
    
    
    @IBOutlet weak var closeBtnCons: NSLayoutConstraint!
    
    private var completion:((_ clsName: String?) -> ())?
    
    
    //点击返回
    @IBAction func returnBtnClick(_ sender: AnyObject) {
        
        scrollView.setContentOffset(CGPoint(x:0,y:0), animated: true)
        
        returnBtnCons.constant = 0
        closeBtnCons.constant = 0
        
        UIView.animate(withDuration: 0.25, animations: { 
            self.layoutIfNeeded()
            self.returnBtn.alpha = 0
            }) { _ in
                self.returnBtn.alpha = 1
                self.returnBtn.isHidden = true
        }
    }
    
    //点击关闭
    @IBAction func close(_ sender: AnyObject) {
        
        //removeFromSuperview()
        hideButtons()
    }
    
    //点击更多
    @objc func clickMore() {
        
        let p = CGPoint(x: scrollView.bounds.width, y: 0)
        
        scrollView.setContentOffset(p, animated: true)
        
        returnBtn.isHidden = false
        
        let margin = scrollView.bounds.width / 6
        
        returnBtnCons.constant -= margin
        closeBtnCons.constant += margin
        
        UIView.animate(withDuration: 0.25) { 
            self.layoutIfNeeded()
        }
    }
    
    @objc func btnClick(button: WBComposeTypeButton) {
        print("点我了!!!\(button.clsName)")
        
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        
        let v = scrollView.subviews[page]
        
        for (i, btn) in v.subviews.enumerated() {
            
            let anim: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewScaleXY)
            
            let scale = (btn == button) ? 2 : 0.2
            
            anim.toValue = NSValue(cgPoint: CGPoint(x: scale, y: scale))
            
            anim.duration = 0.5
            
            btn.pop_add(anim, forKey: nil)
            
            let animAlpha: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
            animAlpha.toValue = 0.2
            animAlpha.duration = 0.5
            
            btn.pop_add(animAlpha, forKey: nil)
            
            if i == 0 {
                
                animAlpha.completionBlock = { (_,_) in
                    
                    print("动画完成，展现控制器")
                    self.completion?(button.clsName)
                }
            }
            
        }
        
    }
    
    let buttonInfos = [["imageName":"tabbar_compose_idea","title":"文字","clsName":"WBComposeViewController"],
                               ["imageName":"tabbar_compose_photo","title":"图片/视频"],
                               ["imageName":"tabbar_compose_weibo","title":"长微博"],
                               ["imageName":"tabbar_compose_lbs","title":"签到"],
                               ["imageName":"tabbar_compose_review","title":"点评"],
                               ["imageName":"tabbar_compose_more","title":"更多","actionName":"clickMore"],
                               ["imageName":"tabbar_compose_friend","title":"朋友圈"],
                               ["imageName":"tabbar_compose_wbcamera","title":"微博相机"],
                               ["imageName":"tabbar_compose_music","title":"音乐"],
                               ["imageName":"tabbar_compose_shooting","title":"拍摄"]]
    
    class func composeTypeView() -> WBComposeTypeView {
        
        let nib = UINib(nibName: "WBComposeTypeView", bundle: nil)
        
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! WBComposeTypeView
        
        //xib 默认加载的frame 是 600 ＊ 600
        v.frame = UIScreen.main.bounds

        return v
        
    }
    
    
    func show(completion:@escaping (_ clsName: String?) -> ())  {
        
        self.completion = completion
        
        guard let vc = UIApplication.shared.keyWindow?.rootViewController else {
            return
        }
        vc.view.addSubview(self)
        showCurrentView()
    }
    
    override func awakeFromNib() {
        setupUi()
    }
}

extension WBComposeTypeView {
    
    func showCurrentView()  {
    
        let anim: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        anim.fromValue = 0
        anim.toValue = 1
        anim.duration = 0.25
        
        pop_add(anim, forKey: nil)
        showButtons()
    }
    
    func showButtons()  {
        
        let v = scrollView.subviews[0]
        
        for (i,btn) in v.subviews.enumerated() {
            
            let anim: POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            anim.fromValue = btn.center.y + 400
            anim.toValue = btn.center.y
            anim.springBounciness = 8
            anim.springSpeed = 10
            
            anim.beginTime = CACurrentMediaTime() + CFTimeInterval(i) * 0.025
            btn.pop_add(anim, forKey: nil)
            
        }
        
    }
    
    func hideButtons() {
        
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        
        let v = scrollView.subviews[page]
        
        for(i,btn) in v.subviews.enumerated().reversed() {
            
            let anim: POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            
            anim.fromValue = btn.center.y
            anim.toValue = btn.center.y + 350
            
            anim.beginTime = CACurrentMediaTime() + CFTimeInterval(v.subviews.count - i) * 0.025
            
            btn.pop_add(anim, forKey: nil)
            
            if i == 0 {
                
                anim.completionBlock = {(_,_) in
                    self.removeCuttentView()
                }
            }
        }
        
    }
    func removeCuttentView()  {
        
        let anim: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        anim.fromValue = 1
        anim.toValue = 0
        anim.duration = 0.25
        
        pop_add(anim, forKey: nil)

        anim.completionBlock = {(_,_)  in
            self.removeFromSuperview()
        }
    }
}

extension WBComposeTypeView {
    
    
    func setupUi() {
        
        layoutIfNeeded()
        let rect = scrollView.bounds
        
        for i in 0..<2 {
            let v = UIView(frame: rect.offsetBy(dx: CGFloat(i) * rect.width,  dy: 0))
            
            addButtons(v: v, ids: i * 6)
            
            scrollView.addSubview(v)
        }
        scrollView.contentSize = CGSize(width: 2 * rect.width, height: 0)
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.showsVerticalScrollIndicator = false
        scrollView.bounces = false
        scrollView.isPagingEnabled = true
        scrollView.isScrollEnabled = false
    }
    
    func addButtons(v: UIView,ids: Int)  {
        let count = 6
        for i in ids..<(ids + count) {
            
            if i >= buttonInfos.count {
                break
            }
            
            let dict = buttonInfos[i]
            
            guard let imagename = dict["imageName"],
                let title = dict["title"] else {
                
                    continue
                    
            }
            
            let btn = WBComposeTypeButton.composeTypeButton(imageName: imagename, title: title)
            
            v.addSubview(btn)
            
            if let actionName = dict["actionName"] {
                btn.addTarget(self, action: Selector(actionName), for: .touchUpInside)
            }else {
                btn.addTarget(self, action: #selector(btnClick), for: .touchUpInside)
            }
            
            btn.clsName = dict["clsName"]
        }
        
        let btnSize = CGSize(width: 100, height: 100)
        let margin = (v.bounds.width - 3 * btnSize.width) / 4
        
        for(i, btn) in v.subviews.enumerated() {
            
            let col = i % 3
            
            let y = i > 2 ? v.bounds.height - btnSize.height : 0
            let x = CGFloat(col + 1) * margin + CGFloat(col) * btnSize.width
            
            btn.frame = CGRect(x: x, y: y, width: btnSize.width, height: btnSize.height)
            
        }
     }
    
}
